import re

import django_filters
from django.db.models import Q
from rest_framework.pagination import PageNumberPagination


CARNO_PATTERN = re.compile(r'^[京津沪渝辽吉黑冀鲁豫晋陕甘闽粤桂川云贵苏浙皖湘鄂赣青新宁蒙藏琼][A-Z][0-9A-Z]{5}$')
NAME_PATTERN = re.compile(r'^[\u4e00-\u9fa5]+$')


def normalize_carno(carno):
    return carno.replace(' ', '').upper()


class CustomPagination(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'size'
    max_page_size = 50


class RecordFilter(django_filters.FilterSet):
    carno_or_owner = django_filters.CharFilter(method='search',
                                               label='输入车牌号或车主姓名')

    @staticmethod
    def search(queryset, name, value):
        return queryset.filter(Q(carno__exact=normalize_carno(value)) |
                               Q(owner__contains=value))

    # class Meta:
    #     model = Record
    #     fields = ()

    # @property
    # def qs(self):
    #     parent = super(RecordFilter, self).qs
    #     q = Q()
    #     carno = self.request.query_params.get('carno')
    #     if carno:
    #         carno = normalize_carno(carno)
    #         q |= Q(carno=carno)
    #     owner = self.request.query_params.get('owner')
    #     if owner:
    #         q |= Q(owner__icontains=owner)
    #     return parent.filter(q)
